package com.lzp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;


@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        // Cors配置
        CorsConfiguration config = new CorsConfiguration();
        // 1. 设置请求域名
        config.addAllowedOrigin("http://localhost:8080"); // 本地ip
        config.addAllowedOrigin("http://www.mtv.com:8080");
        config.addAllowedOrigin("http://www.mtv.com");
        config.addAllowedOrigin("http://www.music.com:8080");
        config.addAllowedOrigin("http://www.music.com");
        config.addAllowedOrigin("*"); // 任意

        // 2. 设置允许的header
        config.addAllowedHeader("*");

        // 3. 设置允许请求的方法
        config.addAllowedMethod("*");

        // 4. 设置是否发送cookie
        config.setAllowCredentials(true);

        // 为URL添加路由
        UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource();
        corsSource.registerCorsConfiguration("/**", config);

        return new CorsFilter(corsSource);
    }
}
